package org.wutopia.labcloud.domain.order.mq.consumer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.seata.rm.tcc.api.BusinessActionContext;
import org.apache.seata.spring.annotation.GlobalTransactional;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;
import org.wutopia.labcloud.domain.order.constant.OrderStatusType;
import org.wutopia.labcloud.domain.order.dao.OrderMainDao;
import org.wutopia.labcloud.domain.order.dao.OrderProductRDao;
import org.wutopia.labcloud.domain.order.dao.entity.OrderMain;
import org.wutopia.labcloud.domain.order.dao.entity.OrderProductR;
import org.wutopia.labcloud.service.api.service.seata.TccProductService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

@Slf4j
@Service
@RocketMQMessageListener(
        topic = "ORDER-TOPIC",
        selectorExpression = "timeout",  // 消费多个Tag
        consumerGroup = "order-consumer-group"
)
public class OrderTimeoutConsumer implements RocketMQListener<Long> {

    private OrderMainDao orderMainDao;

    private OrderProductRDao orderProductRDao;


    @DubboReference
    private TccProductService tccProductService;


    @Override
    @GlobalTransactional
    public void onMessage(Long orderId) {
        log.info("收到订单超时消息: ID={}", orderId);
        // 订单超时
        // 1. 修改订单状态
        UpdateWrapper<OrderMain> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", orderId);
        updateWrapper.set("status", OrderStatusType.TIME_OUT);
        orderMainDao.update(updateWrapper);

        // 2. 退回冻结库存
        QueryWrapper<OrderProductR> q = new QueryWrapper<>();
        q.eq("order_id", orderId);
        List<OrderProductR> orderProductRS = orderProductRDao.selectList(q);

        BusinessActionContext actionContext = new BusinessActionContext();


        for (OrderProductR r : orderProductRS) {
            Map<String, Object> map = new HashMap<>();
            map.put("productId", r.getProductId());
            map.put("frozen", r.getProductAmount());
            actionContext.setActionContext(map);
            tccProductService.stockpileFrozenReturn(actionContext, r.getProductId(), r.getProductAmount());
        }
    }
}
